package com.xtravel.common.helper;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class AsyncLoadImageTask extends AsyncTask<String, Integer, Bitmap> {
	private ImageView imgView;
	private Handler handler;

	public AsyncLoadImageTask(ImageView view, Handler handler) {
		imgView = view;
		this.handler = handler;
	}

	@Override
	protected Bitmap doInBackground(String... args) {
		Bitmap bitmap = null;
		try {
			URL myFileUrl = new URL(args[0]);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setConnectTimeout(6000);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			if (conn.getResponseCode() == 200) {
				InputStream is = conn.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (imgView != null && result != null) {
			imgView.setImageBitmap(result);
		}

		super.onPostExecute(result);
		if (this.handler != null) {
			Message msg = new Message();
			msg.what = 1;
			msg.obj = result;
			this.handler.sendMessage(msg);
		}
	}
}
